/*
 * @Author: sdq 483657864@qq.com
 * @Date: 2025-04-17 17:01:38
 * @LastEditors: sdq 483657864@qq.com
 * @LastEditTime: 2025-04-19 09:50:45
 * @FilePath: \ranyu_anchor_new\src\store\modules\agroa\modules\userStatus.ts
 * @Description: 音量监听
 */
import { type UID } from "agora-rtc-sdk-ng";
/**
 * @description ActiveUser - 活跃用户对象
 */
interface ActiveUser {
  level: number;
  uid: UID;
}
export const agoraVolumeIndicatorListener = async () => {
  // 动态导入，减少不必要的加载
  const { agoraClient } = await import("../initAgoraSdk");
  const { useRemoteStore } = await import("@/store");
  const { useLiveStatusStore } = await import("@/store");
  const { useVoiceConfigStore } = await import("@/store");
  const { handleError } = await import("@/agroa");
  const voiceConfigStore = useVoiceConfigStore();
  const userStatusStore = useLiveStatusStore();
  const remoteStore = useRemoteStore();
  /**
   * @description mountVolumeIndicatorListener - 音量变化指示器（每2秒触发）
   */
  const mountVolumeIndicatorListener = () => {
    try {
      // 启用音量指示器
      agoraClient.value?.enableAudioVolumeIndicator(); //  默认每2秒触发
      agoraClient.value?.on("volume-indicator", (result) => {
        // 过滤出大于40的用户
        const activeUsers = result.filter((item) => item.level > 40);
        updateActiveRemoteUsers(activeUsers);
        if (activeUsers.length > 0) {
          console.log(result);
          ElMessage.success(`用户${JSON.stringify(activeUsers)}正在讲话`);
        }
        const isMeSpeaking = activeUsers.some((item) => item.uid === voiceConfigStore.uid);
        updateMySpeakingStatus(isMeSpeaking);
        if (isMeSpeaking) {
          // ElMessage.success("我在讲话");
        }
      });
    } catch (error) {
      handleError("音量指示器监听失败", error);
    }
  };
  /**
   * 更新活跃用户列表
   * @param {ActiveUser[]}activeUsers
   */
  const updateActiveRemoteUsers = (activeUsers: ActiveUser[]) => {
    const activeLists = activeUsers.map((item) => item.uid);
    remoteStore.updateActiveSpeakers(activeLists);
  };
  /**
   * 更新当前用户活跃状态
   * @param {boolean}status - 是否活跃
   */
  const updateMySpeakingStatus = (status: boolean) => {
    userStatusStore.changeSpeakingStatus(status);
  };
  return {
    mountVolumeIndicatorListener,
  };
};
